package org.gikolet.ch2.android.viewer;

import java.util.LinkedList;

import org.gikolet.ch2.android.R;

import com.google.inject.Inject;

import android.app.AlertDialog;
import android.content.Context;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public abstract class Ch2Viewer extends AbstractViewer {

	public static final int MENU_SETTINGS = 999;

	private boolean backKeyEvent = false;

	private LinkedList<BackCommand> backEventLinkedList = new LinkedList<BackCommand>();

	@Inject
	private Context context;

	public Ch2Viewer() {
	}

	@Override
	public boolean createMenu(Menu menu) {
		// 板一覧更新メニューの追加
		MenuItem settingsMenu = menu.add(0, MENU_SETTINGS, 0,
				R.string.MENU_SETTINGS);
		settingsMenu.setIcon(android.R.drawable.ic_menu_manage);

		return true;
	}

	@Override
	public boolean onMenuItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case MENU_SETTINGS:
			doSettings();
			return true;

		default:
			return false;
		}
	}

	protected void putBackCommand(BackCommand backCommand) {
		this.backEventLinkedList.add(backCommand);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (backEventLinkedList.isEmpty()) {
				if (!this.backKeyEvent) {
					this.backKeyEvent = false;
				} else {
					Toast.makeText(this.context, R.string.BACK_CLOSE_WARNING,
							Toast.LENGTH_LONG).show();
					this.backKeyEvent = true;
				}
			} else {
				BackCommand bc = this.backEventLinkedList.poll();
				bc.back(this);
			}
			this.backKeyEvent = false;

			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	private void doSettings() {
		assert this.context != null : "context is null.";

		new AlertDialog.Builder(this.context).setTitle("設定").setMessage("未実装")
				.setPositiveButton("OK", null).show();
	}
}
